﻿using Feature.YiGuo.Framework.API.Controllers;
using Feature.YiGuo.Framework.Contract;
using System;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using WebApplication1.Core;

namespace WebApplication1.Controllers
{
    public class GatewayController : BaseController
    {
        [HttpGet]
        public async Task<HttpResponseMessage> Execute(string system)
        {
            var request = Request;
            var forwardUriAsString = "";

            var gatewayUrl = BootStartup.RoutingTable["main"];
            var gatewaySystemUrl = string.Format("{0}/{1}", gatewayUrl, system);

            if (!BootStartup.RoutingTable.ContainsKey(system))
            {
                var result = new Response
                {
                    Code = "-1",
                    Message = "请求URL无效",
                    IsSuccessful = false
                };
                
                return Request.CreateResponse(result);
            }
            else
            {
                var routeUri = BootStartup.RoutingTable[system];

                if (system == "main")
                {
                    forwardUriAsString = request.RequestUri.ToString().Replace(gatewaySystemUrl, gatewayUrl);
                }
                else
                {
                    forwardUriAsString = request.RequestUri.ToString().Replace(gatewaySystemUrl, routeUri);
                }
            }

            request.RequestUri = new Uri(forwardUriAsString);

            var client = new HttpClient();
            if (request.Method == HttpMethod.Get)
                request.Content = null;
            var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
            return response;
        }
    }
}
